package dao;

import classes.Market;
import classes.Tip;
import classes.Vrsta;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.*;

public class VrstaDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qInsert, qSelectAll, qDelete, qSelectVrsta;
	private static WebResource service;
	
	public VrstaDAO(Connection c) throws Exception {
		this.c = c;
		qInsert= c.prepareStatement("INSERT INTO vrsta(idVrsta, naziv, Tip_idTip) VALUES(null, ?, ?)");
		qSelectAll = c.prepareStatement("SELECT * FROM vrsta");
		qDelete = c.prepareStatement("DELETE FROM vrsta WHERE idTip=?");
		qSelectVrsta = c.prepareStatement("SELECT * FROM vrsta WHERE idTip = ?");
	}

	public int insertVrsta(Vrsta v) throws Exception {
		if (v==null)
			throw new Exception("Nije moguce dodati nepostojecu vrstu!");
		qInsert.setString(1, v.getNaziv());
		qInsert.setInt(2, v.getTip().getIdTip());
		try{
			int r= qInsert.executeUpdate();
			return r;
		}
		catch(Exception ex){
			throw new Exception("Greska kod dodavanja vrste!");
		}
	}
	
	public Vrsta selectVrsta(int id) throws Exception{
		qSelectVrsta.setInt(1, id);
		ResultSet rs = qSelectVrsta.executeQuery();
		if(rs.next()==false)
			throw new Exception("Vratio null");
		Vrsta v = new Vrsta();
		v.setIdVrsta(rs.getInt("idVrsta"));
		v.setNaziv(rs.getString("naziv"));
		v.setTip(DAOFactory.getTipDAO().selectTip(rs.getInt("Tip_idTip")));		
		return v;
	}
	
	public List<Vrsta> selectSveVrste() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<Vrsta> vrste = new ArrayList<Vrsta>();
		while (rs.next()){
			Vrsta v= new Vrsta();
			v.setIdVrsta(rs.getInt("idVrsta"));
			v.setNaziv(rs.getString("naziv"));
	//		Tip tip= service.path("webservices").path("tipovi").path("tip").path(rs.getString("Tip_idTip")).accept(MediaType.APPLICATION_XML).get(Tip.class);
			v.setTip(DAOFactory.getTipDAO().selectTip(rs.getInt("Tip_idTip")));
			vrste.add(v);
		}
		return vrste;
	}

	public int deleteVrsta(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}



}
